package com.zzzzzz.posts;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.stereotype.Repository;

import com.zzzzzz.BaseDao;
import com.zzzzzz.common.page.Page;

@Repository
public class TagDao extends BaseDao{
	private final static String ADD = "insert into tag(name, refer_count, status) values(:name, :referCount, :status)";
	private final static String EDIT = "update tag set refer_count = referCount+:referCountChange where id = :tagId";
	private final static String EDIT_STATUS_BY_ID = "update tag set status = ? where id = ?";
	
	private final static String FIND_ID_BY_NAME = "select id from tag where name = ? and status = ?";
	private final static String FIND_BY_NAME = "select id, name, refer_count from tag where name = ? and status = ?";
	
	private final static String FIND_ORDERBY_REFERCOUNT = "select id,name,refer_count from tag order by refer_count desc";
	private final static String FIND_ORDERBY_REFERCOUNT_COUNT = "select count(1) from tag";
	
	protected class TagViewRowMapper implements RowMapper<TagView> {
		public TagView mapRow(ResultSet rs, int rn) throws SQLException {
			TagView tagView = new TagView();
			tagView.setId(rs.getInt("id"));
			tagView.setName(rs.getString("name"));
			tagView.setReferCount(rs.getInt("refer_count"));
			return tagView;
		}
	}
	
	public void add(Tag tag){
		int id = this.updateForIntKey(ADD, tag);
		tag.setId(id);
	}
	
	public void edit(TagForm tagForm){
		this.update(EDIT, tagForm);
	}
	
	public void editStatusById(Integer id){
		this.update(EDIT_STATUS_BY_ID, id);
	}
	
	public Integer findIdByName(String name){
		return findInt(FIND_ID_BY_NAME, name);
	}
	
	public TagView findByName(String name){
		return findOne(FIND_BY_NAME, new TagViewRowMapper(), name);
	}
	
	public Page<TagView> findOrderByReferCount(Page<TagView> page){
		MapSqlParameterSource paramMap = new MapSqlParameterSource();
		
		StringBuilder sql = new StringBuilder(FIND_ORDERBY_REFERCOUNT);
		sql.append(limit(paramMap,page));
		
		page = findPage(page,sql.toString(),FIND_ORDERBY_REFERCOUNT_COUNT,paramMap,new TagViewRowMapper());
		return page;
	}
}

